package com.imageService;


import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;

import com.google.appengine.api.blobstore.*;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;


import com.google.appengine.api.files.*;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;

import com.sun.jimi.core.*;


public class ImageHandlerBean implements Serializable{
	
	private String width;
	private String height;
	private String provider;
	private String imagePath;
	
	
	public String getWidth() {
		return width;
	}



	public void setWidth(String width) {
		this.width = width;
	}



	public String getHeight() {
		return height;
	}



	public void setHeight(String height) {
		this.height = height;
	}



	public String getProvider() {
		return provider;
	}



	public void setProvider(String provider) {
		this.provider = provider;
	}



	public String getImagePath() {
		return imagePath;
	}



	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}


	public void resize() throws IOException, JimiException	
	{
		if(this.provider.matches("blitline"))
		{
			resizeBlitline();
		}
		else if (this.provider.matches("cloudinary"))
		{
			resizeCloudinary();
		}
		else if (this.provider.matches("Google"))
		{
			resizeGoogle();
		}
		else
		{
			
		}
	}
	public String resizeCloudinary() 
	{
		
		System.out.println("donwload started");
		
		String baseURL = "http://res.cloudinary.com/seerc/image/upload";
		String urlWidth = "/w_"+this.width;
		String urlHeight = ",h_"+this.height+"/";
		String imageName = "Fotis_Gonidis.jpg";
		
		// http://res.cloudinary.com/seerc/image/upload/w_120,h_120/Fotis_Gonidis.png   This is the download url
	//	URL url = new URL(baseURL+urlWidth+urlHeight+imageName);
		this.imagePath = baseURL+urlWidth+urlHeight+imageName;
		return baseURL+urlWidth+urlHeight+imageName;
	//	return "";
//		//Download foto		
//        Image image = ImageIO.read(url);
//        ImageIO.write((RenderedImage) image, "jpg", new File("fotis_image.jpg"));
//        System.out.println("download finished");
	}
	
	public String resizeBlitline()
	{

		 try {
	            // Send data
			 	String my_app_id = "3YtrhUBS3_yJ6Wps5bW5S5g";
			 	
			 	//blur image
			 //	String json = "{ \"application_id\": \"" + my_app_id+ "\", \"src\" : \"http://www.google.com/logos/2011/yokoyama11-hp.jpg\", \"functions\" : [ {\"name\": \"blur\", \"params\" : {\"radius\" : 0.0, \"sigma\" : 2.0}, \"save\" : { \"image_identifier\" : \"MY_CLIENT_ID\" }} ]}";
			 	
			 	//rotate image
			 	String json = "{ \"application_id\": \"" + my_app_id+ "\", \"src\" : \"http://res.cloudinary.com/seerc/image/upload/v1362131959/Fotis_Gonidis.jpg\", \"functions\" : [ {\"name\": \"resize\", \"params\" : {\"width\" : "+width+", \"height\":"+height+"}, \"save\" : { \"image_identifier\" : \"MY_CLIENT_ID\" }} ]}";
			 	String content = " { \"json\" :" + json + "} ";
			 	System.out.println(content);
			 	
	            URL url = new URL("http://api.blitline.com/job");
	            URLConnection conn = url.openConnection();
	            // Let the run-time system (RTS) know that we want input.
	            conn.setDoInput (true);

	            // Let the RTS know that we want to do output.
	            conn.setDoOutput (true);
	            // No caching, we want the real thing.
	            conn.setUseCaches (false);

	            // Specify the content type.
	            conn.setRequestProperty
	            ("Content-Type", "application/json");
             conn.addRequestProperty
	            ("ACCEPT", "application/json");
	            
	            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
	            wr.write(content);
	            wr.flush();

	            // Get the response
	            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	            String line;
	            String serverresp = new String();
	            while ((line = rd.readLine()) != null) {
	                System.out.println(line);
	                serverresp =serverresp+line;
	            }
	            String[] parts =   serverresp.split("url\":\"");
	            String[] parts1 = parts[1].split("\"}],\"job");
	            String imageUrl = parts1[0];
	            System.out.println("imageUrl"+imageUrl);
	            Thread.sleep(4000);
	            this.imagePath = imageUrl;
	            System.out.println("imageUrl"+this.imagePath);
	            wr.close();
	            rd.close();
	        } catch (Exception e) {
	            System.out.print(e);
	        }
		 
		return "";
	}
	
	public String resizeGoogle() throws IOException, JimiException
	{

		
//
//		boolean lockForRead = false;
//		String filename = "/gs/psilos/Fotis_Gonidis.jpg";
//		AppEngineFile readableFile = new AppEngineFile(filename);
//		FileReadChannel readChannel = fileService.openReadChannel(readableFile, lockForRead);
//
//		// Read the file in whichever way you'd like
//		BufferedReader reader = new BufferedReader(Channels.newReader(readChannel, "UTF8"));
//		String line = reader.readLine();
//		System.out.println(line);
//
//		readChannel.close();
		
		 FileService fileService = FileServiceFactory.getFileService();
		    GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
		        .setBucket("psilos")
		        .setKey("myfile")
		        .setMimeType("image/jpeg")
		        .setAcl("public_read")
		        .addUserMetadata("myfield1", "my field value");
		    AppEngineFile writableFile =
		        fileService.createNewGSFile(optionsBuilder.build());
		    // Open a channel to write to it
		    boolean lock = true;
		    FileWriteChannel writeChannel =
		        fileService.openWriteChannel(writableFile, lock);
		    // Different standard Java ways of writing to the channel
		    // are possible. Here we use a PrintWriter:
		    PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
		   
		  

		  
		
		
		BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
		BlobKey imageBlobKey = blobStoreService.createGsBlobKey("/gs/psilos/Fotis_Gonidis.jpg");
		
		com.google.appengine.api.images.Image oldImage = ImagesServiceFactory.makeImageFromFilename("/gs/psilos/Fotis_Gonidis.jpg");
		byte[] imageBytes = oldImage.getImageData(); 
		ImagesService imagesService = ImagesServiceFactory.getImagesService();

	    Transform resize = ImagesServiceFactory.makeResize(200, 300);
	    com.google.appengine.api.images.Image newImage = imagesService.applyTransform(resize, oldImage);
        byte[] newImageData = newImage.getImageData();
       
        

		
        out.print(newImageData);
       
        // Close without finalizing and save the file path for writing later
	    out.close();
	    
	    // Now finalize
	    writeChannel.closeFinally();

		return "";
	}
	

}
